package cn.jietuo.juc.c_007_reentrant;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2020/5/7
 * @description: 读写锁实践
 */
public class T07_ReadWriteLock {

    Lock lock = new ReentrantLock();

    static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    static Lock readLock = readWriteLock.readLock();
    static Lock writeLock = readWriteLock.writeLock();

    void read() {
        try {
            readLock.lock();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("read over!");
        } finally {
            readLock.unlock();
        }
    }

    void write(){
        try {
            writeLock.lock();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("write over!");
        }finally {
            writeLock.unlock();
        }
    }

    public static void main(String[] args) {
        T07_ReadWriteLock t = new T07_ReadWriteLock();
        Thread[] threads = new Thread[100];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(t::read);
        }
        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }
        new Thread(t::write).start();

    }
}
